package au.com.spaceandtime.coordinates;

import au.com.spaceandtime.time.HourMinSec;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: whale
 * Date: 19/10/13
 * Time: 12:41 PM
 */
public class Horizontal {
    private static final Logger LOG = Logger.getLogger(Horizontal.class.getName());

    private double altitude = 0d;
    private double azimuth = 0d;


    public Horizontal(DegMinSec altitude, DegMinSec azimuth) {
        this.altitude = altitude.degreesToDecimal();
        this.azimuth = azimuth.degreesToDecimal();
    }

    /**
     * Convert from Alt, Az to Right Ascention, Declination
     * @param geoLatitude
     * @return
     */
    public Equatorial convertToEquatorial(double geoLatitude) {
        LOG.setLevel(Level.FINEST);

        Equatorial equatorial = new Equatorial();

        double latRadians = Math.toRadians(geoLatitude);
        LOG.info("latRadians " + latRadians);

        double altRadians = Math.toRadians(altitude);
        LOG.info("altRadians " + altRadians);

        double azRadians = Math.toRadians(azimuth);
        LOG.info("azRadians " + azRadians);

        double sindec = Math.sin(altRadians)*Math.sin(latRadians) + Math.cos(altRadians)*Math.cos(latRadians)*Math.cos(azRadians);
        LOG.info("sindec " + sindec);

        double decRadians = Math.asin(sindec);
        LOG.info("dec(rads) " + decRadians);

        double decDegrees = Math.toDegrees(decRadians);
        LOG.info("dec(degrees) " + decDegrees);

        double y = - Math.cos(altRadians)*Math.cos(latRadians)*Math.sin(azRadians);
        LOG.info("y " + y);

        double x = Math.sin(altRadians) - (Math.sin(latRadians)*sindec);
        LOG.info("x " + x);

        double a = Math.atan2(y, x);
        LOG.info("a " + a);

        double b = Math.toDegrees(a);
        LOG.info("b " + b);

        double sinAzimuth = Math.sin(azRadians);
        LOG.info("sinAzimuth " + sinAzimuth);

        double hourDegrees = b - 360*Math.floor(b/360d);

        if (sinAzimuth > 0) {
           // hourDegrees =  360 - hourDegrees;
        }

        LOG.info("HA (degs) " + hourDegrees);

        HourMinSec hourAngle = new HourMinSec(hourDegrees);

        equatorial.setDeclination(decDegrees);
        equatorial.setHourAngle(hourAngle);


        return equatorial;
    }

    public double getAzimuthDecimal() {
        return azimuth;
    }

    public double getAltitudeDecimal() {
        return altitude;
    }
}
